<template>
  <div>
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <br />
    <template :rules="rules">
      <el-input
        v-model="search"
        size="medium"
        placeholder="输入关键字搜索"
        style="width:30%;margin-top:10px;"
      >
        <el-button slot="append" icon="el-icon-search" @click="searchOwners"></el-button>
      </el-input>
    </template>
    <!-- 新增业主弹窗体 -->
    <el-dialog title="业主信息" :visible.sync="dialogVisible" width="30%">
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="owner"
        :rules="rules"
        ref="owner"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="owner.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="owner.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.number="owner.phone" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="owner.idCard" maxlength="18" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="居住地址" prop="address">
          <owneraddress @getAddressid="showAddress"></owneraddress>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="info" @click="resetOwner()">重 置</el-button>
        <el-button type="primary" @click="submitForm('owner')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 信息表 -->
    <!-- .filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase())) -->
    <el-table :data="tableData" style="width: 100%" :stripe="true" row-key="ownerId">
      <el-table-column label="Date" prop="createtime"></el-table-column>
      <el-table-column label="Name" prop="name">
        <template slot-scope="scope">
          <p v-html="scope.row.name"></p>
        </template>
      </el-table-column>
      <el-table-column label="Gender" prop="gender" :formatter="formatSex"></el-table-column>
      <el-table-column label="Phone" prop="phone"></el-table-column>
      <el-table-column label="IdCard" prop="idCard"></el-table-column>
      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>
<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js, json文件,图片文件等等)
// 例如: import 《组件名称》from '《组件路径》';
import owneraddress from "@/views/common/owneraddress.vue";
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    owneraddress: owneraddress
  },
  props: {},
  data() {
    return {
      tableData: [],
      currentPage: 1,
      search: "",
      oldsearch: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dialogVisible: false,
      labelPosition: "right",
      addOrUpdate: "",
      owner: {
        ownerId: null,
        name: "",
        gender: "",
        idCard: "",
        phone: "",
        blockId: "",
        unitId: "",
        roomId: ""
      },
      ownerIds: [],
      rules: {
        name: [
          { required: true, message: "请输入业主姓名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
        idCard: [
          { required: true, message: "请填写身份证号", trigger: "blur" },
          { min: 18, max: 18, message: "长度为18个字符", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          { type: "number", message: "电话号码必须为数字值", trigger: "blur" }
        ],
        address: [
           { validator: (rule, value, callback)=>{
             if(this.owner.blockId==""){
               callback(new Error('请选择居住地址!'));
             }else{
               callback()
             }
           }, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    showAddress(data) {
      this.owner.blockId = data[0];
      this.owner.unitId = data[1];
      this.owner.roomId = data[2];
      console.log("添加业主",this.owner)
    },
    // 页大小转变
    sizeChangeHandle(val) {
      console.log(`每页 ${val} 条`);
    },
    // 修改当前页
    currentChangeHandle(val) {
      console.log(`每页 ${val} 条`);
    },
    //性别转换
    formatSex(row, column, cellValue, index) {
      return row.gender == 0 ? "男" : row.gender == 1 ? "女" : "未知";
    },
    // 点击修改
    handleEdit(index, row) {
      this.owner.ownerId = row.ownerId;
      this.owner.name = row.name;
      this.owner.gender = row.gender;
      this.owner.idCard = row.idCard;
      this.owner.phone = row.phone * 1;
      this.dialogVisible = true;
      this.addOrUpdate = "update";
    },
    // 点击新增
    handleAdd() {
      this.dialogVisible = true;
      this.addOrUpdate = "add";
      this.resetOwner();
    },
    // 搜索业主
    searchOwners() {
      // 过滤掉重复搜索和无效搜索
      if (this.search == "" || this.search == null) {
        this.getDataList();
        return;
      }
      if (this.search.length > 0 && this.oldsearch != this.search) {
        this.oldsearch = this.search;
        this.$http({
          url: this.$http.adornUrl("/manager/owner/search/" + this.search),
          method: "post",
          data: this.$http.adornData(this.owner, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                if (data.data != null) {
                  this.tableData = data.data;
                } else {
                  this.$message({
                    message: "数据不存在",
                    type: "warning",
                    duration: 1500,
                    onClose: () => {
                      this.getDataList();
                    }
                  });
                }
              }
            });
          } else {
            console.log("添加失败", data);
          }
        });
      }
    },
    // 添加业主
    addOwner() {
      console.log("添加业主",this.owner)
      this.$http({
        url: this.$http.adornUrl("/manager/owner/save"),
        method: "post",
        data: this.$http.adornData(this.owner, false)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dialogVisible = false;
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getDataList();
            }
          });
        } else {
          console.log("添加失败", data);
        }
      });
    },
    // 删除业主
    deleteOwner() {
      this.$http({
        url: this.$http.adornUrl("/manager/owner/delete"),
        method: "post",
        data: this.$http.adornData(this.ownerIds, false)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.ownerIds = [];
          this.getDataList();
        } else {
          this.$message({
            type: "warning",
            message: "删除失败!"
          });
        }
      });
    },
    // 修改业主
    updateOwner() {
      this.$http({
        url: this.$http.adornUrl("/manager/owner/update"),
        method: "post",
        data: this.$http.adornData(this.owner, false)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dialogVisible = false;
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getDataList();
            }
          });
        } else {
          console.log("修改失败", data);
        }
      });
    },
    // 点击删除
    handleDelete(index, row) {
      this.ownerIds = [row.ownerId];
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (this.ownerIds != null) {
            this.deleteOwner();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 提交表单数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 添加业主
          console.log("添加业主",this.owner)
          if (this.addOrUpdate == "add") {
            this.addOwner();
          } else if (this.addOrUpdate == "update") {
            // 修改业主
            this.updateOwner();
          }
        } else {
          return false;
        }
      });
    },
    // 重置表单数据
    resetOwner() {
      this.owner.ownerId = null;
      this.owner.name = "";
      this.owner.gender = null;
      this.owner.idCard = "";
      this.owner.phone = null;
      this.owner.blockId = ""
      this.owner.unitId = ""
      this.owner.roomId = ""
    },

    // 获取数据列表
    getDataList() {
      console.log("获取数据列表")
      this.$http({
        url: this.$http.adornUrl("/manager/owner/list"),
        method: "get"
      }).then(({ data }) => {
        console.log(data)
        var temp = data.page.list;
        this.tableData = temp;
        this.totalPage = data.page.totalCount;
      });
    }
  },
  activated() {
    this.getDataList();
  } // 如果页面有keep-alive缓存功能, 这个函数会触发
};
</script>
<style>
body {
  margin: 0;
}
</style>
